/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.common.web.action.student;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ar.uba.fi.posgrado.common.exception.RepeatedInstanceException;
import ar.uba.fi.posgrado.common.model.IdentificationType;
import ar.uba.fi.posgrado.common.model.Student;
import ar.uba.fi.posgrado.common.service.IdentificationTypeService;
import ar.uba.fi.posgrado.common.service.StudentService;
import ar.uba.fi.posgrado.common.web.form.student.StudentForm;
import ar.uba.fi.posgrado.economy.model.Customer;
import ar.uba.fi.posgrado.economy.model.Terms;
import ar.uba.fi.posgrado.economy.service.CustomerService;

/**
 * Action para crear alumnos.<br>
 * 
 * @author pablo.tortorella
 * 
 */
public class CreateStudentAction extends Action {

	/** Logger */
	private static Logger logger = Logger.getLogger(CreateStudentAction.class);

	private StudentService studentService;

	private IdentificationTypeService identificationTypeService;

	private CustomerService customerService;

	/**
	 * @return the identificationTypeService
	 */
	public IdentificationTypeService getIdentificationTypeService() {
		return identificationTypeService;
	}

	/**
	 * @param identificationTypeService
	 *            the identificationTypeService to set
	 */
	public void setIdentificationTypeService(
			IdentificationTypeService identificationTypeService) {
		this.identificationTypeService = identificationTypeService;
	}

	/**
	 * @return the studentService
	 */
	public StudentService getStudentService() {
		return studentService;
	}

	/**
	 * @return the customerService
	 */
	public CustomerService getCustomerService() {
		return customerService;
	}

	/**
	 * @param studentService
	 *            the studentService to set
	 */
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	/**
	 * @param customerService
	 *            the customerService to set
	 */
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	/**
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Por crear un alumno ...");
		}
		StudentForm form = (StudentForm) actionForm;

		Student student = new Student();
		student.setName(form.getName());
		student.setSurname(form.getSurname());
		student.setPersonalId(form.getPersonalId());
		student.setAddress(form.getAddress());
		student.setNationality(form.getNationality());
		student.setEmail(form.getEmail());
		student.setEmail2(form.getEmail2());
		student.setPhone(form.getPhone());
		student.setWorkPhone(form.getWorkPhone());
		student.setMobile(form.getMobile());
		student.setPosition(form.getPosition());
		student.setCompany(form.getCompany());
		student.setDegree(form.getDegree());
		student.setComplete(form.getComplete());

		IdentificationType idType = this.identificationTypeService.getById(Long
				.parseLong(form.getSelectedIdType()));
		student.setIdType(idType);

		try {
			if (form.isCreateCustomer()) {
				// Crea un cliente nuevo
				Customer customer = new Customer();
				customer.setAddress(student.getAddress());
				customer.setCorporateName(student.getCorporateName());
				customer.setName(student.getFullName());
				customer.setDocument(student.getPersonalId());
				customer.setTerms(Terms.CONSUMIDOR_FINAL.toStringValue());
				customer.setEmail(student.getEmail());
				customer.setPhone(student.getPhone());
				customer.setMobile(student.getMobile());
				customer.setContact(student.getFullName());
				this.studentService.createStudentAndCustomer(student, customer);
			} else {
				this.studentService.create(student);
			}
		} catch (RepeatedInstanceException e) {
			logger
					.info("Intentando crear un alumno con nombre, apellido y documento existentes. Devolviendo error...");
			ActionMessages errors = new ActionMessages();
			errors
					.add("student.name", new ActionMessage(e.getMessage(),
							false));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
		logger.info("Alumno " + student.getFullName() + ", con documento "
				+ student.getPersonalId() + " creado");

		return mapping.findForward("success");
	}
}
